package com.yonyou.ucf.mdf.app.isvdxq.firstpart.pandian.service;

import com.yonyou.ucf.mdf.app.isvdxq.ReturnResult.DataResult;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.RFIDCodeDetail.mapper.CoderfidMapperImpl;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.RFIDCodeDetail.service.RfidCodeDetailService;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.guize.service.GuiZeService;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.location.controller.LocationController;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.location.entity.Location;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.location.entity.LocationEntity;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.location.mapper.LocationMapperImpl;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.location.service.LocationEntityService;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.pandian.entity.Checkdiff;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.pandian.entity.Checkresult;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.pandian.entity.Checkresult2;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.pandian.entity.Checkstockarea;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.pandian.mapper.*;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.pandian.model.CheckAreaAndCheckLocation;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.pandian.model.CheckresultDTO;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.pandian.model.CreatStockDto;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.pandian.model.checkstockMainOrder;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.stock.mapper.StockMapperImpl;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.stock.model.productInfo;
import com.yonyou.ucf.mdf.app.isvdxq.other.entity.WarehouseEntity;
import com.yonyou.ucf.mdf.app.isvdxq.other.mapper.impl.WarehouseMapperImpl;
import com.yonyou.ucf.mdf.app.isvdxq.secondpart.entity.EpcEntity;
import com.yonyou.ucf.mdf.app.isvdxq.secondpart.model.CheckAreaBean;
import com.yonyou.ucf.mdf.app.isvdxq.secondpart.model.CheckResultBean;
import com.yonyou.ucf.mdf.app.isvdxq.secondpart.model.CheckScanBean;
import com.yonyou.ucf.mdf.app.isvdxq.secondpart.service.EpclistService;
import com.yonyou.ucf.mdf.app.isvdxq.utils.MyTool;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class CheckresultService {

    @Autowired
    LocationEntityService locationEntityService;

    @Autowired
    CheckresultMapperImpl checkresultMapper;
    @Autowired
    CheckscanMapperImpl checkscanMapper;
    @Autowired
    CheckstockareaMapperImpl checkstockareaMapper;
    @Autowired
    CheckstockMapperImpl checkstockMapper;
    @Autowired
    LocationMapperImpl locationMapper;
    @Autowired
    RfidCodeDetailService rfidCodeDetailService;
    @Autowired
    CoderfidMapperImpl coderfidMapper;

    @Autowired
    CheckdiffMapperImpl checkdiffMapper;
    @Autowired
    WarehouseMapperImpl warehouseMapper;
    @Autowired
    GuiZeService guiZeService;
    @Autowired
    EpclistService epclistService;

    @Autowired
    StockMapperImpl stockMapper;



    private static final Logger logger = LoggerFactory.getLogger(LocationController.class);

    /**
     * 添加测试
     *
     * @return
     */
    public Checkresult add(Checkresult model, String tenant_id) throws Exception {
        String Id = MyTool.getRandomId();
        Checkresult res = null;
        model.setId(Id);
        int resInt = checkresultMapper.InsertObj(model);
        if (resInt == 0) return res;
        res = checkresultMapper.selectById(Id, tenant_id);
        return res;
    }


    /**
     * 创建盘点单及盘点单明细
     *
     * @param isFupan  1主单  2复盘单
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public DataResult CreatCheckStock(CreatStockDto CreatStockDto, String tenant_id, String isFupan) {
        DataResult dataResult = null;
        try {
            String checkCode = "", checkNo = "";
            if(isFupan.equals("1")) { //盘点单
                checkNo = MyTool.GenerateCode();
                checkCode = "C" + checkNo;
            } else if(isFupan.equals("2")){ //复盘单
                checkNo = CreatStockDto.getCheckNo();
                checkCode = CreatStockDto.getcCheckCode();
            }
            String checkid = MyTool.getRandomId();
            List<CreatStockDto.locationlist> locationlists = CreatStockDto.getLocationarr();

            //查询orgid
            String orgid = "";
            if (CreatStockDto.getWarehouseId() != null && !CreatStockDto.getWarehouseId().equals("") && !CreatStockDto.getWarehouseId().equals("null")) {
                WarehouseEntity warehouseEntity = warehouseMapper.selectById(Long.parseLong(CreatStockDto.getWarehouseId()), tenant_id);
                if (warehouseEntity != null) {
                    orgid = warehouseEntity.getOrg();
                } else {
                    dataResult = new DataResult(0, "创建盘点单参数错误！");
                    return dataResult;
                }
            } else {
                dataResult = new DataResult(0, "创建盘点单参数错误！");
                return dataResult;
            }
            //sourceType 单据源类型(1区域2货架3货位4整库) 1、4时locationlists为区域信息  2时locationlists为货架信息  3时locationlists为货架信息
            List<String> localids = new ArrayList<>();
            String sourceType = CreatStockDto.getSourceType();
            if(null == sourceType){
                sourceType = "";
            }
            if(sourceType.equals("")){
                dataResult = new DataResult(0, "创建盘点单参数错误！");
                return dataResult;
            }
//            if(sourceType.equals("3")){ //盘点位置为货位
//                for (CreatStockDto.locationlist item : locationlists) {
//                    localids.add(item.getLocationID());
//                }
//            } else { //盘点位置为区域、货架
//                //查询盘点区域、货架下的货位信息
//                //仓库下的所有货位信息
//                List<Location> allLocationList = locationMapper.getLocationByWarehouseId(CreatStockDto.getWarehouseId(), tenant_id);
//                for (CreatStockDto.locationlist item : locationlists) {
//                    //过虑区域、货架下的货位信息
//                    List<Location> locationOptionalList = allLocationList.stream()
//                            .filter( x -> ( null!= x.getPath() && x.getPath().contains("|"+item.getLocationID()+"|") ) ) //&& ( null != x.getLevel() && x.getLevel()==3)
//                            .collect(Collectors.toList());
//                    if(null != locationOptionalList && locationOptionalList.size()>0){
//                        for(Location location : locationOptionalList){
//                            localids.add(location.getId());
//                        }
//                    }
//                }
//
//            }
//            if(null != localids && localids.size()>0) {
//                List<productInfo> rfidCodeList = stockMapper.selectCoderfidBylocaid(localids, tenant_id);
//                if (null == rfidCodeList || rfidCodeList.size() == 0) {
//                    dataResult = new DataResult(0, "创建盘点单盘点范围下没有物料！");
//                    return dataResult;
//                }
//            } else {
//                dataResult = new DataResult(0, "创建盘点单盘点范围下没有物料！");
//                return dataResult;
//            }

            if (locationlists != null && locationlists.size() > 0) {
                //checkType:盘点类型(0自由盘点1任务盘点)
                String checkType = "1";
                checkstockMapper.InsertcheckStock(checkType, isFupan, checkNo, checkCode, CreatStockDto.getcRemark(), CreatStockDto.getSourceType(), CreatStockDto.getUserid(), "",
                        CreatStockDto.getWarehouseName(), CreatStockDto.getWarehouseId(), tenant_id, "", 0, CreatStockDto.getUserid(), CreatStockDto.getUserid(), checkid, orgid);

                List<CheckAreaBean> checkAreaBeanList = new ArrayList<>();
                for (CreatStockDto.locationlist item : locationlists) {
                    String CheckAreaID = MyTool.getRandomId();
                    CheckAreaBean checkAreaBean = new CheckAreaBean();
                    checkAreaBean.setCheckId(checkid);
                    checkAreaBean.setId(CheckAreaID);
                    checkAreaBean.setDr(0);
                    checkAreaBean.setVersion(0);
                    checkAreaBean.setiStatus("0"); //未盘点
                    checkAreaBean.setTenant_id(tenant_id);
                    checkAreaBean.setCreator(CreatStockDto.getUserid());
                    checkAreaBean.setCreate_time(MyTool.GenerateTime());
                    checkAreaBean.setModify_time(MyTool.GenerateTime());
                    checkAreaBean.setModifier(CreatStockDto.getUserid());
                    checkAreaBean.setLocationID(item.getLocationID());
                    checkAreaBean.setLocationCode(item.getLocationCode());
                    checkAreaBean.setLocationName(item.getLocationName());
                    checkAreaBean.setRfid_code(item.getRFIDCode());
                    checkAreaBean.setWarehouse_code(item.getWarehouseCode());
                    checkAreaBean.setWarehouse_name(item.getWarehouseName());
                    checkAreaBeanList.add(checkAreaBean);
                }
                checkstockareaMapper.insertBatch(checkAreaBeanList);
                dataResult = new DataResult(1, "创建盘点单信息成功");
                return dataResult;
            } else {
                dataResult = new DataResult(0, "创建盘点单参数错误！");
                return dataResult;
            }
        } catch (Exception e) {
            dataResult = new DataResult(0, "创建盘点单信息失败！");
            return dataResult;
        }
        // return dataResult;
    }


    /**
     * 创建复盘单
     * @param stockId  创建复盘单的盘点单id
     * @param userId
     * @param tenant_id
     * @return
     */
    public DataResult CreatFuPanCheckStock(String stockId, String userId, String tenant_id) {
        DataResult dataResult = null;

        //查找盘点单信息
        checkstockMainOrder checkStockBean = checkstockMapper.GetCheckStockById(stockId, tenant_id);
        if(null != checkStockBean) {
            String checkNo = checkStockBean.getCheckNo();
            String fuPanCheckCode = ""; //复盘单号

            String checkCode = checkStockBean.getcCheckCode();
            if (StringUtils.isNotEmpty(checkCode)) {
                if (checkCode.contains("-")) {
                    String[] res = checkCode.split("-");
                    fuPanCheckCode = res[0] + "-" + (Integer.parseInt(res[1]) + 1);
                } else {
                    fuPanCheckCode = checkCode + "-1";
                }
            } else {
                dataResult = new DataResult(0, "创建复盘单参数错误！");
                return dataResult;
            }

            List<CreatStockDto.locationlist> locationlists = new ArrayList<>();
            //创建复盘单
            //查找盘点单的盘点范围
            List<Checkstockarea> checkstockareaList = checkstockareaMapper.GetCheckStockAreaByCheckId(stockId, tenant_id);
            if (null != checkstockareaList && !checkstockareaList.isEmpty()) {
                for (Checkstockarea checkstockarea : checkstockareaList) {
                    CreatStockDto.locationlist location = new CreatStockDto.locationlist();
                    location.setLocationID(checkstockarea.getLocationID());
                    location.setLocationCode(checkstockarea.getLocationCode());
                    location.setLocationName(checkstockarea.getLocationName());
                    location.setWarehouseCode(checkstockarea.getWarehouse_code());
                    location.setWarehouseName(checkstockarea.getWarehouse_name());
                    location.setRFIDCode(checkstockarea.getRfid_code());
                    locationlists.add(location);
                }
                //dr, checkType, ShenheStatus, `iStatus`,`create_time`,`modify_time`,"
                CreatStockDto checkStockDto = new CreatStockDto();
                checkStockDto.setCheckNo(checkNo);
                checkStockDto.setcCheckCode(fuPanCheckCode);
                checkStockDto.setWarehouseId(checkStockBean.getWarehouseId());
                checkStockDto.setWarehouseName(checkStockBean.getWarehousename());
                checkStockDto.setcRemark(checkStockBean.getcRemark());
                checkStockDto.setParentCheckID(checkStockBean.getId());
                checkStockDto.setSourceType(checkStockBean.getSourceType());
                checkStockDto.setCheckType("1");
                checkStockDto.setLocationarr(locationlists);
                checkStockDto.setUserid(userId);

                dataResult = this.CreatCheckStock(checkStockDto, tenant_id, "2");
                if (dataResult.getStatus() == 1) {
                    //复盘单创建成功，修改盘点单的状态
                    try {
                        int i = checkstockMapper.UpdatSheheStatus(stockId, "2", userId, tenant_id);
                        if (i > 0) {
                            dataResult = new DataResult(1, "复盘单创建成功，复盘单号：“" + fuPanCheckCode + "”！");
                        } else {
                            dataResult = new DataResult(0, "复盘单创建失败！");
                        }
                    } catch (Exception e) {
                        dataResult = new DataResult(0, "创建盘点单失败！");
                        throw new RuntimeException(e);
                    }
                } else {
                    String message = dataResult.getMessage();
                    message = message.replace("创建盘点单", "创建复盘单");
                    dataResult.setMessage(message);
                }
            } else {
                dataResult = new DataResult(0, "复盘单创建失败！当前盘点单没有要复盘的位置信息，不生成复盘单，请检查当前盘点单！");
            }
        } else {
            dataResult = new DataResult(0, "参数错误！未查询到当前盘点单,请检查数据！");
        }

        return dataResult;
    }

    /**
     * 盘点单审核
     * @param stockId 盘点单ID
     * @param userId
     * @param tenant_id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public DataResult checkStockShenhe(String stockId, String userId, String tenant_id) {
        DataResult dataResult = null;

        //查找盘点单信息
        checkstockMainOrder checkStockBean = checkstockMapper.GetCheckStockById(stockId, tenant_id);
        if(null != checkStockBean) {
            Integer shenheStatus = checkStockBean.getShenheStatus();
            if (null == shenheStatus) {
                shenheStatus = 0;
            }
            if (shenheStatus == 1) {
                dataResult = new DataResult(0, "当前盘点单已审核！");
                return dataResult;
            }

            List<Checkdiff> checkdiffList = new ArrayList<>();
            List<String> pankuiIDs = new ArrayList<>();
            List<String> panyingIDs = new ArrayList<>();
            //查找盘点单的异常盘点结果：盘盈、盘亏的盘点结果，并对盘盈、盘亏的盘点结果进行处理
            List<Checkresult2> checkYichangResultList = checkresultMapper.selectYichangBycheckId(stockId, tenant_id);
            if (null != checkYichangResultList && checkYichangResultList.size() > 0) {
                for (Checkresult2 checkresult2 : checkYichangResultList) {
                    String batch_no = checkresult2.getBatch_no(); //提交用友到货入库的批次号
                    if (null == batch_no) {
                        batch_no = "";
                    }
                    String checkStatus = checkresult2.getCheckstatus();
                    if (!batch_no.equals("")) { //已经提交用友的入库
                        Checkdiff checkdiff = new Checkdiff();
                        checkdiff.setId(MyTool.getRandomId());
                        checkdiff.setCheckResultID(checkresult2.getId());
                        checkdiff.setCheckCode(checkStockBean.getcCheckCode());
                        checkdiff.setCheckID(checkresult2.getCheckID());
                        checkdiff.setCoderfid(checkresult2.getCoderfID());
                        checkdiff.setRfidCode(checkresult2.getRfid_code());
                        checkdiff.setProductName(checkresult2.getProduct_name());
                        checkdiff.setProduct_id(checkresult2.getProduct_id());
                        checkdiff.setProduct_sku_id(checkresult2.getProduct_sku_id());
                        checkdiff.setWarehouseId(checkresult2.getWarehouse_id());
                        checkdiff.setLocaltionID(checkresult2.getStorkLocationID());
                        checkdiff.setRemark(checkresult2.getRemark());
                        checkdiff.setCheckstatus(checkStatus);
                        checkdiff.setLabelCount(checkresult2.getLabelCount());
                        checkdiff.setStatus("0");
                        checkdiff.setCreator(userId);
                        checkdiff.setModifier(userId);

                        checkdiffList.add(checkdiff);
                    }

                    if (checkStatus.equals("0")) { //盘亏
                        pankuiIDs.add(checkresult2.getCoderfID());
                    } else if (checkStatus.equals("2")) { //盘盈
                        panyingIDs.add(checkresult2.getCoderfID());
                    }
                }
            }

            //写入盘点差异数据，并更新盘盈、盘亏数据的状态
            try {
                if (null != checkdiffList && checkdiffList.size() > 0) {
                    //写入盘点差异数据
                    checkdiffMapper.insertBatch(checkdiffList, tenant_id);
                }
                if (null != pankuiIDs && pankuiIDs.size() > 0) {
                    //盘亏时库存处理
                    coderfidMapper.UpdateYingKui(pankuiIDs, userId, "6", tenant_id);
                }
                if (null != panyingIDs && panyingIDs.size() > 0) {
                    //盘盈时库存处理
                    coderfidMapper.UpdateYingKui(panyingIDs, userId, "", tenant_id);
                }

                //更新盘点单的审核状态：审核通过
                checkstockMapper.UpdatSheheStatus(stockId, "1", userId, tenant_id);

                dataResult = new DataResult(1, "盘点单审核成功！");
                dataResult.setDataList(checkdiffList); //盘点差异数据
            } catch (Exception e) {
                dataResult = new DataResult(0, "盘点单审核失败！");
                throw new RuntimeException(e);
            }
        } else {
            dataResult = new DataResult(0, "参数错误！");
        }
        return dataResult;
    }


    /**
     * 任务盘点或者自由盘点提交第二次盘点
     * todo 是否支持多盘点点批量提交 目前不支持
     * 全仓库盘点, 整单数据清理
     *
     * @param checkresultList
     * @param tenantid
     * @param isWarehouse
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public DataResult CommitCheckResult(CheckresultDTO checkresultList, String tenantid, boolean isWarehouse) {
        DataResult dataResult = new DataResult(0, "参数异常");
        if (checkresultList == null) return dataResult;
        try {
            List<CheckresultDTO.CheckTaskBean> dataList = checkresultList.getData();
            // 盘点点 每次提交只有一个
            List<String> checkIds = dataList.stream().map(it -> it.getCheckLocationID()).distinct().collect(Collectors.toList());
            if (checkIds.size() != 1) {
                dataResult.setMessage("仅支持单盘点点盘点");
                return dataResult;
            }
            String checkLocationID = dataList.get(0).getCheckLocationID();
            List<String> locationIds = new ArrayList<>();
            if (!isWarehouse) {
                locationIds = locationEntityService.GetLocationListByPath(checkLocationID, tenantid).stream().map(it -> it.getId()).collect(Collectors.toList());
            }

            // 查询盘点单子单的内容
            List<Checkstockarea> checkstockareaList = checkstockareaMapper.GetCheckStockAreaByCheckId(checkresultList.getCheckID(), tenantid);
            List<CheckAreaAndCheckLocation> CheckAreaIDs = GetCheckAreaIDs(checkstockareaList, dataList, tenantid);
            // 需要根据扫描货位绑定好的的id 返回对应的 盘点单子单ID
            String checkNum = "1";//盘点次数
            List<Checkresult> checkresultList1 = checkresultMapper.selectBycheckID(checkresultList.getCheckID(), tenantid);
            if (checkresultList1 != null && checkresultList1.size() > 0) {
                Checkresult checknumCount = checkresultList1.stream().max(Comparator.comparing(Checkresult::getCheckNum)).get();
                Integer num = checknumCount.getCheckNum();
                checkNum = String.valueOf(num + 1);
                // 删除盘点点历史数据
                List<Checkresult> checkresultListdel = new ArrayList<>();
                if (isWarehouse) checkresultListdel = checkresultList1; //全仓库盘点, 整单数据清理
                else if (!isWarehouse && locationIds.size() > 0) {
                    checkresultListdel = checkresultMapper.getByCheckAreaIds(checkresultList.getCheckID(), locationIds, tenantid);
                }
                List<String> resultidArr = checkresultListdel.stream().map(e -> e.getId()).collect(Collectors.toList());
                if (resultidArr.size() > 0) {
                    checkresultMapper.DelcheckresultByids(resultidArr, tenantid); //软删除
                }
            }
            // 处理盘点数据
            CheckDataWork(checkresultList, tenantid, "", CheckAreaIDs, checkNum);

            // 更新盘点区域数据状态
            List<String> CheckAreaIds = new ArrayList<>();
            for (CheckAreaAndCheckLocation item : CheckAreaIDs) {
                CheckAreaIds.add(item.getId());
            }
            if (CheckAreaIds.size() > 0)
                checkstockareaMapper.UpdateareaStatusByIds(CheckAreaIds, checkresultList.getUserid(), "1", tenantid);
            // 更新盘点单状态
            String statuscheck = checkstockMapper.SelCheckStatusByid(checkresultList.getCheckID(), tenantid);
            if (statuscheck.equals("0")) {
                checkstockMapper.UpdatCheckStatus(checkresultList.getCheckID(), checkresultList.getUserid(), "1", tenantid);
            }

            dataResult = new DataResult(1, "盘点信息提交信息成功");
        } catch (Exception e) {
            dataResult = new DataResult(0, "盘点信息提交信息失败!");
        }

        return dataResult;
    }


    /// <summary>
    /// 获取盘点点Id 仓库直接返回仓库Id
    /// </summary>
    /// <param name="checkArea"></param>
    /// <param name="locationID_scan"></param>
    /// <returns></returns>
    public String GetCheckAreaID(List<Checkstockarea> checkArea, String locationID_scan, String tenantId) {
        String res = "";
        if (StringUtils.isEmpty(locationID_scan)) return res;
        LocationEntity locationEntity = locationEntityService.getLocationById(locationID_scan, tenantId);
        if (locationEntity != null && locationEntity.getLevel() == 0) return locationEntity.getId();

        List<String> ids = new ArrayList<>();
        ids = locationEntityService.GetLocationIDParents(locationID_scan, ids, tenantId);
        if (ids.size() == 0 || checkArea.size() == 0) return res;
        for (String key : ids) {
            Checkstockarea tempCheckArea = checkArea.stream().filter(it -> it.getLocationID().equals(key)).findFirst().orElse(null);
            if (tempCheckArea != null) return tempCheckArea.getId();
        }
        return res;
    }

    /// <summary>
    /// 获取盘点单子单Id集合
    /// </summary>
    /// <param name="checkArea"></param>
    /// <param name="locationID_scan"></param>
    /// <returns></returns>
    public List<CheckAreaAndCheckLocation> GetCheckAreaIDs(List<Checkstockarea> checkArea, List<CheckresultDTO.CheckTaskBean> checkDatas, String tenantId) throws Exception {
        // 区域盘点单或者全仓盘点单按照区域或者全仓处理
        List<CheckAreaAndCheckLocation> checkAreaIds = new ArrayList<>();
        List<String> locationIds = checkDatas.stream().map(it -> it.getStorkLocationID()).distinct().collect(Collectors.toList());

        List<LocationEntity> LocationList = new ArrayList<>();
        if (locationIds.size() > 0)
            LocationList = locationMapper.selectLocationByIds(locationIds, tenantId);
        for (Checkstockarea item : checkArea
        ) {
            List<LocationEntity> locationOptionalList = LocationList.stream().filter(x -> x.getPath().contains(item.getLocationID())).collect(Collectors.toList());
            for (LocationEntity itemSon : locationOptionalList
            ) {
                CheckAreaAndCheckLocation itemCheckArea = new CheckAreaAndCheckLocation();
                itemCheckArea.setId(item.getId()); //盘点区域表主键
                itemCheckArea.setCheckAreaId(item.getLocationID()); //盘点区域表对应的货位ID
                itemCheckArea.setCheckLocation(itemSon.getId()); //实际盘点货位ID
                checkAreaIds.add(itemCheckArea);
            }
        }
        return checkAreaIds;
    }

    /**
     * 自由盘点提交盘点结果
     * editlast: 2023-02-01 by chen
     *
     * @param checkresultList
     * @param tenantid
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public DataResult CommitCheckResultRealTime(CheckresultDTO checkresultList, String tenantid) {
        DataResult dataResult = new DataResult(0, "参数异常");

        try {
            if (checkresultList != null) {
                String checkNo = MyTool.GenerateCode();
                String checkCode = "C" + checkNo;
                String checkid = MyTool.getRandomId();
                String CheckAreaID = MyTool.getRandomId();
                checkresultList.setCheckID(checkid);
                checkresultList.setCheckCode(checkCode);
                String sourceType = "0";
                if (checkresultList.getLevel() == 1) {
                    sourceType = "1";
                } else if (checkresultList.getLevel() == 2) {
                    sourceType = "2";
                } else if (checkresultList.getLevel() >= 3) {
                    sourceType = "3";
                }
                //checkType:盘点类型(0自由盘点1任务盘点)
                String checkType = "0";
                //添加盘点单主单
                checkstockMapper.InsertcheckStock(checkType,"1", checkNo, checkCode, "", sourceType, checkresultList.getUserid(),
                        checkresultList.getUserid(), checkresultList.getWarehousename(), checkresultList.getWarehouseId(),
                        checkresultList.getTenant_id(), "", 0, checkresultList.getUserid(), checkresultList.getUserid(),
                        checkid, checkresultList.getOrg_id());

                //添加盘点单子单
                CheckAreaBean checkAreaBean = new CheckAreaBean();
                checkAreaBean.setCheckId(checkid);
                checkAreaBean.setId(CheckAreaID);
                checkAreaBean.setDr(0);
                checkAreaBean.setVersion(0);
                checkAreaBean.setiStatus("1"); //盘点中
                checkAreaBean.setTenant_id(tenantid);
                checkAreaBean.setCreator(checkresultList.getUserid());
                checkAreaBean.setCreate_time(MyTool.GenerateTime());
                checkAreaBean.setModify_time(MyTool.GenerateTime());
                checkAreaBean.setModifier(checkresultList.getUserid());
                checkAreaBean.setLocationID(checkresultList.getLocationID());
                checkAreaBean.setLocationCode(checkresultList.getLocationCode());
                checkAreaBean.setLocationName(checkresultList.getLocationName());
                checkAreaBean.setRfid_code(checkresultList.getLocationRfidCode());
                checkAreaBean.setWarehouse_code(checkresultList.getWarehousecode());
                checkAreaBean.setWarehouse_name(checkresultList.getWarehousename());
                List<CheckAreaBean> checkAreaBeanList = new ArrayList<>();
                checkAreaBeanList.add(checkAreaBean);
                checkstockareaMapper.insertBatch(checkAreaBeanList);

                // 处理盘点数据
                CheckDataWork(checkresultList, tenantid, CheckAreaID, null, "1");

            }
            dataResult = new DataResult(1, "盘点信息提交信息成功");
        } catch (Exception e) {
            dataResult = new DataResult(0, "盘点信息提交信息失败!");
        }

        return dataResult;
    }

    /**
     * 盘点数据处理
     *
     * @param checkresultList
     * @param tenantid
     * @param checkNum
     * @throws Exception
     */
    private void CheckDataWork(CheckresultDTO checkresultList, String tenantid, String checkAreaID, List<CheckAreaAndCheckLocation> checkAreaIDs, String checkNum) throws Exception {

        List<CheckresultDTO.CheckTaskBean> dataList = checkresultList.getData();
        String checkId = checkresultList.getCheckID();
        String checkCode = checkresultList.getCheckCode();
        // 批量盘点记录数据写入
        List<CheckresultDTO.CheckTaskBean> statusList = dataList.stream().filter(it -> it.getTagStatus().equals("2") || it.getTagStatus().equals("1")).distinct().collect(Collectors.toList());
        List<CheckScanBean> myscanList = new ArrayList<>();
        for (CheckresultDTO.CheckTaskBean item : statusList) {
            if (StringUtils.isEmpty(checkAreaID) && checkAreaIDs != null) {
                String StorkLocationID = item.getStorkLocationID();
                Optional<CheckAreaAndCheckLocation> cACLocationOptional = checkAreaIDs.stream().filter(x -> x.getCheckLocation().equals(StorkLocationID)).findFirst();
                checkAreaID = cACLocationOptional.get().getId();//盘点区域的主键ID
            }
            CheckScanBean entity = new CheckScanBean();
            entity.setId(MyTool.getRandomId());
            entity.setCheckID(checkId);
            entity.setCheckAreaID(checkAreaID);
            entity.setCoderfID(item.getCoderfID());
            entity.setProduct_id(item.getProduct_id());
            entity.setProduct_sku_id(item.getProduct_sku_id());
            entity.setLabelCount(item.getLabelCount());
            entity.setCheckLocationID(item.getCheckLocationID());
            entity.setStorkLocationID(item.getStorkLocationID());
            entity.setScanWay(Integer.valueOf(item.getScanWay()));
            entity.setTagStatus(item.getTagStatus());
            entity.setTenant_id(tenantid);
            entity.setModifier(tenantid);
            entity.setModify_time(MyTool.GenerateTime());
            entity.setCreator(tenantid);
            entity.setCreate_time(MyTool.GenerateTime());
            entity.setCheckUser(tenantid);
            entity.setRemark(item.getRemark());
            entity.setCheckRemark(item.getRemark());
            entity.setCheckNum(Integer.valueOf(checkNum));
            entity.setCheckstatus(item.getStatus());
            entity.setDr(0);
            entity.setPk_temp("");
            entity.setVersion(0);
            myscanList.add(entity);
        }
        if (myscanList.size() > 0)
            checkscanMapper.insertBatch(myscanList);

        // 货位数据批量修改  如果多扫的话 一致 移到盘点货位（多扫异常处理）
        List<String> epcIds = dataList.stream().filter(it -> it.getType() == 4).map(it -> it.getCoderfID())
                .distinct().collect(Collectors.toList());
        List<EpcEntity> epcEntityList = epclistService.SelectByIds(epcIds, tenantid);
        for (EpcEntity item : epcEntityList) {
            CheckresultDTO.CheckTaskBean tempEntity = dataList.stream().filter(it -> it.getCoderfID().equals(item.getId())).findAny().orElse(null);
            if (tempEntity != null) {
                String huojiaID = locationEntityService.GetHuojiaID(tempEntity.getCheckLocationID(), tenantid);
                item.setShelf_id(huojiaID);
                item.setLocation_id(tempEntity.getCheckLocationID());
            }
            item.setWarehouse_id(checkresultList.getWarehouseId());
            item.setWarehouse_code(checkresultList.getWarehousecode());
            item.setModifier(tenantid);
            item.setRfid_status(1);
        }
        if (epcEntityList.size() > 0)
            epclistService.EditForShangjia(epcEntityList, tenantid);

        // 批量盘点结果数据写入
        List<CheckResultBean> myDataList = new ArrayList<>();
        for (CheckresultDTO.CheckTaskBean item : dataList) {
            if (StringUtils.isEmpty(checkAreaID) && checkAreaIDs != null) {
                String StorkLocationID = item.getStorkLocationID();
                Optional<CheckAreaAndCheckLocation> cACLocationOptional = checkAreaIDs.stream().filter(x -> x.getCheckLocation().equals(StorkLocationID)).findFirst();
                checkAreaID = cACLocationOptional.get().getId(); //盘点区域的主键ID
            }
            CheckResultBean entity = new CheckResultBean();
            entity.setId(MyTool.getRandomId());
            entity.setCheckID(checkId);
            entity.setCheckCode(checkCode);
            entity.setCheckAreaID(checkAreaID);
            entity.setCoderfID(item.getCoderfID());
            entity.setProduct_id(item.getProduct_id());
            entity.setProduct_sku_id(item.getProduct_sku_id());
            entity.setLabelCount(item.getLabelCount());
            entity.setCheckLocationID(item.getCheckLocationID());
            entity.setStorkLocationID(item.getStorkLocationID());
            entity.setScanWay(item.getScanWay());
            entity.setTagStatus(item.getTagStatus());
            entity.setTenant_id(tenantid);
            entity.setModifier(tenantid);
            entity.setModify_time(MyTool.GenerateTime());
            entity.setCreator(tenantid);
            entity.setCreate_time(MyTool.GenerateTime());
            entity.setCheckUser(tenantid);
            entity.setRemark(item.getRemark());
            entity.setCheckRemark(item.getRemark());
            entity.setCheckNum(checkNum);
            entity.setiHandelMethod("0");
            entity.setCheckstatus(item.getStatus());
            entity.setDr(0);
            entity.setPk_temp("");
            entity.setVersion(0);
            myDataList.add(entity);
        }
        if (myDataList.size() > 0)
            checkresultMapper.insertBatch(myDataList);
    }

    //盘点列表pc
    public DataResult selCheckResult(String checkid, String checkLocationName, String productName, String productunit, String stockunitname, String checkstatus, String iHandelMethod, String scanWay
            , String productskuName, Integer page, Integer pagesize, String tenantid) {
        DataResult dataResult = new DataResult();
        Integer startNumber = (page - 1) * pagesize;
        try {
            List<Checkresult> checkresult = new ArrayList<>();
            List<String> checkLocationArr = new ArrayList<>();
            List<LocationEntity> LocationList = locationMapper.getLocationEntityAll(tenantid);
            //检索位置的
            if (checkLocationName != null && !checkLocationName.equals("")) {
                //查出当前盘点单结果中所有的货位id
                List<Checkresult> checkresultsel = checkresultMapper.selectBycheckID(checkid, tenantid);
                if (checkresultsel != null && checkresultsel.size() > 0) {
                    Map<String, List<Checkresult>> collect = checkresultsel.stream().filter(u -> u.getCheckLocationID() != null && !u.getCheckLocationID().equals(""))
                            .collect(Collectors.groupingBy(Checkresult::getCheckLocationID));
                    for (String key : collect.keySet()) {
                        String locationName = LocationEntityService.GetLocationFullNameEx(key, LocationList, "");
                        if (locationName.contains(checkLocationName)) {
                            checkLocationArr.addAll(Arrays.asList(key));
                        }
                    }
                }
                //取出符合当前搜索条件的盘点结果数据
                if (checkLocationArr == null || checkLocationArr.size() == 0) {
                    dataResult = new DataResult(1, "盘点结果信息查询数据为0条!");
                    return dataResult;
                }
            }

            int checkresultCount = checkresultMapper.selectCheckCount(checkid, checkLocationArr, productName, productunit, stockunitname, checkstatus, iHandelMethod, scanWay, productskuName,
                    tenantid);
            dataResult.setTotalPages(checkresultCount / pagesize + 1);
            dataResult.setTotalSize(checkresultCount);
            checkresult = checkresultMapper.selectBycheckParam(checkid, checkLocationArr, productName, productunit, stockunitname, checkstatus, iHandelMethod, scanWay, productskuName, startNumber,
                    pagesize, tenantid);
            if (checkresult != null && checkresult.size() > 0) {
                for (Checkresult checkresultsel : checkresult) {
                    String LocationID = checkresultsel.getCheckLocationID();
                    if (LocationID != null && !LocationID.equals("")) {
                        String locationName = LocationEntityService.GetLocationFullNameEx(LocationID, LocationList, "");
                        checkresultsel.setCheckLocationName(locationName);
                    }
                    String StorkLocationID = checkresultsel.getStorkLocationID();
                    if (StorkLocationID != null && !StorkLocationID.equals("")) {
                        String locationName = LocationEntityService.GetLocationFullNameEx(StorkLocationID, LocationList, "");
                        checkresultsel.setStorkLocationName(locationName);
                    }
                }
                dataResult = new DataResult(1, "盘点信息查询成功!", checkresult, page, pagesize, checkresult.size(), dataResult.getTotalPages(), dataResult.getTotalSize());
                return dataResult;
            } else {
                dataResult = new DataResult(1, "盘点结果信息查询数据为0条!");
                return dataResult;
            }
        } catch (Exception e) {

            dataResult = new DataResult(0, "盘点结果信息查询失败!");
            //TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            //e.printStackTrace();
        }
        return dataResult;
    }


    //盘点分析表pc
    public DataResult selCheckDiffList(String checkCode, List<String> warehouseIds, String locationname, String productname, String status, String checkstatus, String productskuname, Integer page,
                                       Integer pagesize, String tenantid) {
        DataResult dataResult = new DataResult();
        Integer startNumber = (page - 1) * pagesize;
        try {
            List<Checkdiff> checkdiffList = new ArrayList<>();
            List<LocationEntity> LocationList = locationMapper.getLocationEntityAll(tenantid);
            List<String> checkLocationArr = new ArrayList<>();
            //检索位置的
            if (locationname != null && !locationname.equals("")) {
                //查出当前盘点单结果中所有的货位id
                List<Checkdiff> checkdiffsel = new ArrayList<>();
                if (warehouseIds.size() > 0)
                    checkdiffsel = checkdiffMapper.selectCheckdiff(tenantid, warehouseIds);
                if (checkdiffsel != null && checkdiffsel.size() > 0) {
                    Map<String, List<Checkdiff>> collect = checkdiffsel.stream().filter(u -> u.getLocaltionID() != null && !u.getLocaltionID().equals(""))
                            .collect(Collectors.groupingBy(Checkdiff::getLocaltionID));
                    for (String key : collect.keySet()) {
                        String locationName = LocationEntityService.GetLocationFullNameEx(key, LocationList, "");
                        if (locationName.contains(locationname)) {
                            checkLocationArr.addAll(Arrays.asList(key));
                        }
                    }
                }
                //取出符合当前搜索条件的盘点结果数据
                if (checkLocationArr == null || checkLocationArr.size() == 0) {
                    dataResult = new DataResult(1, "盘点结果信息查询数据为0条!");
                    return dataResult;
                }
            }

            int checkresultCount = checkdiffMapper.selectCheckDiffCount(checkCode, checkLocationArr, productname, status, checkstatus, productskuname, tenantid, warehouseIds);
            dataResult.setTotalPages(checkresultCount / pagesize + 1);
            dataResult.setTotalSize(checkresultCount);
            checkdiffList = checkdiffMapper.selectCheckDiffPage(checkCode, checkLocationArr, productname, status, checkstatus, productskuname, startNumber, pagesize, tenantid, warehouseIds);

            if (checkdiffList != null && checkdiffList.size() > 0) {
                for (Checkdiff checkdiffsel : checkdiffList) {
                    String LocationID = checkdiffsel.getLocaltionID();
                    if (LocationID != null && !LocationID.equals("")) {
                        String locationName = LocationEntityService.GetLocationFullNameEx(LocationID, LocationList, "");
                        checkdiffsel.setLocaltionName(locationName);
                    }
                    String warehouseId = checkdiffsel.getWarehouseId();
                    if (warehouseId != null && !warehouseId.equals("")) {
                        WarehouseEntity warehouseEntity = warehouseMapper.selectById(Long.parseLong(warehouseId), tenantid);
                        if(null != warehouseEntity){
                            checkdiffsel.setWarehouseCode(warehouseEntity.getCode());
                            checkdiffsel.setWarehouseName(warehouseEntity.getWarehouseName());
                        }
                    }
                }
                dataResult = new DataResult(1, "盘点分析信息查询成功!", checkdiffList, page, pagesize, checkdiffList.size(), dataResult.getTotalPages(), dataResult.getTotalSize());
                return dataResult;
            } else {
                dataResult = new DataResult(1, "盘点分析信息查询数据为0条!");
                return dataResult;
            }
        } catch (Exception e) {
            dataResult = new DataResult(0, "盘点分析信息查询失败!");
        }
        return dataResult;
    }

}
